<script setup lang="ts">
import { closeToast, showLoadingToast, showToast, type ActionSheetAction } from 'vant'
import { ref, watch } from 'vue'
import base64ToBlob from 'b64-to-blob'
import { http } from '@/api'
import { nickNameStore, useProfileStore } from '@/stores/prifile'

const profile = ref<ProfileInfo>({} as ProfileInfo)
// 昵称 获取编辑页面共享数据
const storeNickName = nickNameStore()
const nickName = ref('')
nickName.value = storeNickName.nickName
watch(nickName, (newValue, oldValue) => {
  profile.value.name = storeNickName.nickName
  save({
    name: profile.value.name,
    intro: profile.value.intro,
    gender: profile.value.gender,
    birthday: profile.value.birthday,
    real_name: profile.value.real_name
  })
})
// 简介 获取编辑页面共享数据
const store = useProfileStore()
const intro = ref('')
intro.value = store.profileContent
watch(intro, (newValue, oldValue) => {
  profile.value.intro = store.profileContent
  save({
    name: profile.value.name,
    intro: profile.value.intro,
    gender: profile.value.gender,
    birthday: profile.value.birthday,
    real_name: profile.value.real_name
  })
})

// const photoUrl = ref('')

// 保存加载中
const loading = ref(false)
// 修改
// {
//     // name: profile.value.name,
//     // intro: profile.value.intro,
//     gender: profile.value.gender
//     // birthday: profile.value.birthday
//   }
const save = async (params: {}) => {
  try {
    loading.value = true
    console.log(JSON.stringify(profile.value))
    console.log('>>>>' + JSON.stringify(params))
    const res = http.patch<TtResponse<ProfileInfo>>('v1_0/user/profile', params)
    // profile.value = (await res).data.data
    console.log(JSON.stringify(res))

    loading.value = false
    // 更新返回页面本地昵称
    const user = Tt.queryUser()
    user.mobile = profile.value.name
    Tt.updateUser(user)
    showToast({ message: '保存成功' })
  } catch (error) {
    console.log(error)
    showToast({ message: '保存失败' })
  } finally {
    loading.value = false
  }
}

const exit = async () => {
  Tt.removeUser()
  Tt.RouterBack()
}
const getProfile = async () => {
  try {
    // 5.1 开启提示
    showLoadingToast({
      message: '正在加载中...',
      duration: 0,
      forbidClick: true
    })
    // 5.2 发请求拿数据
    const res = await http.get<TtResponse<ProfileInfo>>('/v1_0/user/profile')
    profile.value = res.data.data
    console.log(profile.value)
    // 5.4 取出生日给到页面
    birthday.value = res.data.data.birthday.split('-')
    // 更新网络获取到的昵称
    storeNickName.changeNickName(profile.value.name)
    // 更新网络获取到的简介
    store.changeProfileContent(profile.value.intro)
  } finally {
    // 5.3 关闭提示
    closeToast()
  }
}
// 获取个人信息
getProfile()
// 修改头像
const showAvatarSheet = ref(false)
const selectAvatarSheet = async (item: ActionSheetAction, i: number) => {
  if (i === 0) {
    const data = await Tt.pickerPhoto()
    console.log(data)
    onUpdateAvatar(data)
  } else if (i === 1) {
    const data = await Tt.pickerCamera()
    onUpdateAvatar(data)
  }
  showAvatarSheet.value = false
}
// 上传头像
const onUpdateAvatar = async (data: string) => {
  try {
    // 1.1.1 把bas464编码转成图片文件
    const image = base64ToBlob(data, 'image/jpeg')

    // 1.1.2 把文件放入formData对象
    const fd = new FormData()
    fd.append('photo', image, Date.now() + '.jpeg')

    // 1.1.3 调用接口
    showLoadingToast({
      message: '正在上传中...',
      duration: 0,
      forbidClick: true
    })
    const res = await http.patch<{ photo: string }>('/v1_0/user/photo', fd)
    profile.value.photo = res.data.photo
    // 1.1.4 修改原生侧的头像
    const user = Tt.queryUser()
    user.photo = res.data.photo
    Tt.updateUser(user)
    showToast('头像上传成功')
  } catch (e) {
    showToast('头像上传失败')
  } finally {
    closeToast()
  }
}

// 2. 选择生日
const showBirthdayPopup = ref(false)
const onChangeBirthday = () => {
  // 2.1 隐藏弹层
  showBirthdayPopup.value = false
  profile.value.birthday = birthday.value.join('-')
  save({
    name: profile.value.name,
    intro: profile.value.intro,
    gender: profile.value.gender,
    birthday: profile.value.birthday,
    real_name: profile.value.real_name
  })
}
// 2.2 定义一个属性去和datePicker双向绑定
const now = new Date()
const birthday = ref([
  now.getFullYear().toString(),
  String(now.getMonth() + 1),
  now.getDate().toString()
])

//3.选择性别
const Genderlist = [
  { text: '男', value: '男' },
  { text: '女', value: '女' }
]
const showgenderPopup = ref(false)
const gender = ref<string[]>([])
// 选择性别弹窗
const onChangegender = (data: { selectedValues: string[] }) => {
  showgenderPopup.value = false
  profile.value.gender = data.selectedValues[0]
  profile.value.gender === '男' ? (profile.value.gender = '1') : (profile.value.gender = '0')
  save({
    name: profile.value.name,
    intro: profile.value.intro,
    gender: profile.value.gender,
    birthday: profile.value.birthday,
    real_name: profile.value.real_name
  })
}
</script>

<template>
  <div>
    <!-- 中间表单部分 -->
    <div class="shangsanceng">
      <!-- 头像部分 -->
      <van-cell title="头像" is-link
        ><van-image
          round
          width="2rem"
          height="2rem"
          :src="profile.photo"
          @click="showAvatarSheet = true"
        ></van-image>
      </van-cell>

      <!-- 选择头像动作弹层 -->
      <van-action-sheet
        v-model:show="showAvatarSheet"
        :actions="[{ name: '相册' }, { name: '拍照' }]"
        cancel-text="取消"
        close-on-click-action
        @select="selectAvatarSheet"
      />
      <van-cell
        title="昵称"
        is-link
        :value="storeNickName.nickName || '未填写'"
        to="profile/edit/:id?"
      />
      <van-cell title="简介" is-link :value="store.profileContent || '未填写'" to="introducing" />
    </div>
    <div class="xialiangceng">
      <!-- 性別 -->
      <van-cell
        v-model="profile.gender"
        title="性别"
        is-link
        :value="(profile.gender == '1' ? '男' : '女') || '未填写'"
        @click="showgenderPopup = true"
      />

      <!-- 选择性别弹层 -->
      <van-popup v-model:show="showgenderPopup" position="bottom">
        <van-picker
          v-model="gender"
          title="选择性别"
          :columns="Genderlist"
          @confirm="onChangegender"
          @cancel="showgenderPopup = false"
        />
      </van-popup>

      <!-- 生日 -->
      <van-cell
        v-model="profile.birthday"
        title="生日"
        is-link
        :value="profile.birthday || '未填写'"
        @click="showBirthdayPopup = true"
      />

      <!-- 选择生日弹层 -->
      <van-popup v-model:show="showBirthdayPopup" position="bottom">
        <van-date-picker
          v-model="birthday"
          title="选择日期"
          :min-date="new Date('1980-01-01')"
          :max-date="new Date()"
          @cancel="showBirthdayPopup = false"
          @confirm="onChangeBirthday"
        />
      </van-popup>
    </div>

    <div class="submit" @click="exit">
      <van-button color="linear-gradient(to right, #ff6034, #ee0a24)" size="large">
        退出登录
      </van-button>
    </div>
  </div>
</template>

<style lang="css" scoped>
.shangsanceng {
  margin-bottom: 30px;
}

.submit {
  margin-top: 100px;
  text-align: center;
  padding: 16px;
}
.save {
  margin-top: 20px;
  text-align: center;
  padding: 16px;
}
</style>
